package com.htjc.integral.house.service.impl;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.htjc.integral.common.util.StrUtil;
import com.htjc.integral.common.util.UUIDUtil;
import com.htjc.integral.house.commons.IConstant;
import com.htjc.integral.house.mapper.ConsMapper;
import com.htjc.integral.house.service.IConsService;
import com.htjc.integral.house.util.JsonUtil;
import com.htjc.integral.house.util.ResultModel;
import com.htjc.integral.house.util.enums.AccountReturn;
import com.htjc.integral.model.house.EcBpAccount;
import com.htjc.integral.model.house.EcBpPowerUserIncome;
import com.htjc.integral.model.house.EcBpPowerUserTransfer;

import lombok.extern.slf4j.Slf4j;

@Slf4j(topic = "jfLog")
@Service
public class ConsServiceImpl implements IConsService{

	@Autowired
	ConsMapper consMapper;
	
	 
	@Override
	@Transactional
	public String addConsBalance(JSONObject jsonObject) {	
		String incomeType = jsonObject.getString("INCOME_TYPE");
		String provinceCode = jsonObject.getString("PROVINCE_CODE");
		String consNo = jsonObject.getString("POWER_USER_NO");
		String orgNo = jsonObject.getString("ORG_NO");
		
		if (!IConstant.INCOME_TYPE_01.equals(incomeType) && !IConstant.INCOME_TYPE_02.equals(incomeType) && !IConstant.INCOME_TYPE_03.equals(incomeType)) {
			log.info(">>>>>>>>===查询户号余额失败===<<<<<<<<-未知的业务类型");
			return "-1";
		}
		EcBpPowerUserIncome ecBpPowerUserIncome = new EcBpPowerUserIncome();
		EcBpAccount ecBpAccount = new EcBpAccount();
		
		ecBpPowerUserIncome.setIncomeId(UUIDUtil.getUUID());
		ecBpPowerUserIncome.setPowerUserNo(consNo);
		ecBpPowerUserIncome.setProvinceId(provinceCode);
		ecBpPowerUserIncome.setPowerunitCode(orgNo);
		ecBpPowerUserIncome.setIncomeIntegral(jsonObject.getBigDecimal("INCOME_NUM"));
		ecBpPowerUserIncome.setIncomeType(incomeType);
		ecBpPowerUserIncome.setCreateTime(new Timestamp(System.currentTimeMillis()));
		ecBpPowerUserIncome.setBusinessType(jsonObject.getString("INCOME_SOURCE"));
		ecBpPowerUserIncome.setBusinessId(jsonObject.getString("ACCOUNT_MAIN_ID"));
		ecBpPowerUserIncome.setIncomeStatus(IConstant.INCOME_STATUS_01);
		
		Map<String, Object> map = consMapper.queryConsBalance(provinceCode, consNo, orgNo);
		String accountId = null;
		if (map == null) {
			accountId = consMapper.querySeq(IConstant.SEQ_EC_BP_ACCOUNT);
		} else {
			accountId = (String) map.get("ACCOUNT_ID");
		}
		ecBpAccount.setAccountId(accountId);
		ecBpAccount.setBalance(jsonObject.getBigDecimal("INCOME_NUM"));//收入总金额
		ecBpAccount.setCityId(orgNo);//供电单位
		ecBpAccount.setPowerunitId(orgNo);//结算单位=供电单位？？？？
		ecBpAccount.setProvinceId(provinceCode);//网省编码
		ecBpAccount.setPowerUserNo(consNo);
		
		//记录明细数据
		consMapper.insertConsUserIncome(ecBpPowerUserIncome);
		//更新余额表--退费，冲正后的余额可为负
		consMapper.updateConsAccount(ecBpAccount);
		
		return accountId;
	}
	@Override
	public JSONObject queryConsBalance(String provinceCode, String orgNo, String consNo) {
		Map<String, Object> map = new HashMap<String,Object>();
		try { 
			 map = consMapper.queryConsBalance(provinceCode, consNo, orgNo);
			if (map == null) {
				//如果查询的户号为空 初始化 户号 赠送200000积分
				String accountId = initConsAccount(provinceCode, consNo, orgNo,200000);
				log.info("初始化成功返回值={}",accountId);
				if(!StrUtil.isEmpty(accountId)){
					 map = consMapper.queryConsBalance(provinceCode, consNo, orgNo);
				}
				log.info("查询户号map={}",map);
//				return JSONObject.parseObject(JsonUtil.bean2json(ResultModel.AccountReturnError( AccountReturn.ACCOUNT_ERROR_NOTFOUND)));
			}
		} catch (Exception e) {
			// TODO: handle exception
			log.error("【户号中心 】查询户号积分余额异常 错误信息={}",e.getMessage());
		}
		
		return JSONObject.parseObject(JsonUtil.bean2json(ResultModel.AccountReturnSucceed(map)));
	}

	@Override
	@Transactional
	public JSONObject dedConsBalance(JSONObject jsonObject) {
		String provinceCode = jsonObject.getString("PROVINCE_CODE");
		String consNo = jsonObject.getString("POWER_USER_NO");
		String orgNo = jsonObject.getString("ORG_NO");
		//锁定用户
		
		//判断该户余额是否够扣减
		JSONObject consJson = queryConsBalance(provinceCode, orgNo, consNo);
		
		if (IConstant.ERROR.equals(consJson.getString("code"))) {
			log.info(">>>>>>>>===户号余额扣减===<<<<<<<<-查询该户不存在");
			return null;
		}
		//用户余额
		BigDecimal consBalance = consJson.getJSONObject("content").getBigDecimal("BALANCE");
		//待扣减余额--取绝对值
		BigDecimal dedBalance = jsonObject.getBigDecimal("INCOME_NUM").abs();
		//实际扣减
		BigDecimal balance = null;
		
		if ((consBalance.compareTo(dedBalance) == -1) && (consBalance.compareTo(new BigDecimal(0)) == 1)) {
			balance = consBalance.negate();
		} else if (consBalance.compareTo(dedBalance) >= 0 && consBalance.compareTo(new BigDecimal(0)) == 1) {
			balance = dedBalance.negate();
		} else {
			return null;
		}
		//执行实际的扣减
		EcBpPowerUserTransfer ecBpPowerUserTransfer = new EcBpPowerUserTransfer();
		EcBpAccount ecBpAccount = new EcBpAccount();
		
		String id = UUIDUtil.getUUID();
		
		ecBpPowerUserTransfer.setId(id);
		ecBpPowerUserTransfer.setAccountId(jsonObject.getString("ACCOUNT_MAIN_ID"));
		ecBpPowerUserTransfer.setPowerunitCode(jsonObject.getString("ORG_NO"));
		ecBpPowerUserTransfer.setProvinceId(jsonObject.getString("PROVINCE_CODE"));
		ecBpPowerUserTransfer.setTransferDesc(jsonObject.getString("INCOME_SOURCE"));
		ecBpPowerUserTransfer.setPowerUserNo(jsonObject.getString("POWER_USER_NO"));
		ecBpPowerUserTransfer.setTransferStatus(IConstant.TRANSFER_STATUS_01);
		ecBpPowerUserTransfer.setTransferSum(balance);
		
		ecBpAccount.setBalance(balance);	
		ecBpAccount.setProvinceId(jsonObject.getString("PROVINCE_CODE"));
		ecBpAccount.setCityId(jsonObject.getString("ORG_NO"));
		ecBpAccount.setPowerUserNo(jsonObject.getString("POWER_USER_NO"));
		//落库
		consMapper.updateConsAccount(ecBpAccount);
		consMapper.insertConsTransfer(ecBpPowerUserTransfer);
		
		JSONObject json = new JSONObject();
		json.put("ACCOUNT_DED_ID", id);
		json.put("INCOME_NUM", balance);
		return json;
	}
	
	
	
	
	/**
	 * 初始化户号积分
	 */
	@Override
	@Transactional
	public String initConsAccount(String provinceCode ,String consNo,String orgNo,long balance) {
		// TODO Auto-generated method stub
//		String incomeType = IConstant.INCOME_TYPE_01; //初始化是新增
		log.info("初始化户号积分插入数据库开始===============》数据插入{}",consNo);
		String accountId = null;
		BigDecimal bigBalance = null;
		try {
			
			bigBalance = BigDecimal.valueOf(balance);//如果户号不存在 新增200000 积分
			accountId = consMapper.querySeq(IConstant.SEQ_EC_BP_ACCOUNT);
			log.info("初始化户号积分 记录ID{}",accountId);
			EcBpAccount ecBpAccount = new EcBpAccount();
			ecBpAccount.setAccountId(accountId);
			ecBpAccount.setPowerUserNo(consNo);
			ecBpAccount.setPowerunitId(orgNo);//结算单位=供电单位？？？？
			ecBpAccount.setProvinceId(provinceCode);//网省编码
			ecBpAccount.setCityId(orgNo);//供电单位
			ecBpAccount.setBalance(bigBalance);//初始化积分
//			ecBpAccount.setTotalBalance(bigBalance);
			
			//初始化户号 记录
			int flag = consMapper.insertConsAccount(ecBpAccount);
			if(flag !=  1){
				log.info("初始化户号积分插入数据库 失败！！！！");
			}
			log.info("初始化户号积分插入数据库结束===============》数据插入{}",consNo);
			
			
		} catch (Exception e) {
			// TODO: handle exception
			log.error("初始化户号积分异常 错误信息={}",e.getMessage());
		}
		return accountId;
	}
}
















